<!--
  文件名: BlogWriting.vue
  描述: 这是一个博客编写界面，用于编写博客并发布，参考界面为CSDN
  作者: 白紫铜
  创建日期: 2024-03-29
-->
<template>
<div>
  <el-container>
    <el-aside class="aside" width="150px"></el-aside>
    <el-container>
      <el-main class="main">
        <form @submit.prevent="submitForm">
          <el-col :span="24" style="width: 1050px;">
            <element-tiptap v-model:content="content" :extensions="extensions" lang="zh"></element-tiptap>
          </el-col>
          <div style="margin-bottom: 50px"></div>
          <el-row style="margin-bottom: 20px;">
            <el-col :span="6">
              <el-input v-model="title" placeholder="请输入文章标题"></el-input>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 20px;">
            <el-col :span="12">
              <el-input v-model="summary" placeholder="请输入文章摘要" type="textarea"></el-input>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 20px;">
            <el-col :span="6">
              <el-button class="blog_post" type="primary" @click="chooseCover">选择封面</el-button>
              <div></div>
              <el-image :src="imageUrl" style="height: 90px;width: 160px;background-color: #f0f0f0">
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <!-- 上传头像的input元素 -->
              <input type="file" ref="coverInput" style="display: none" @change="handleCoverChange">
              <vue-cropper
                  ref="cropper"
                  v-if="showCropper"
                  :img="imageUrl"
                  :outputType="'png'"
                  :autoCrop="true"
                  auto-crop-height="100%"
                  auto-crop-width="100%"
                  :centerBox="true"
                  :fixed="true"
                  :canMove="false"
                  :fixedNumber="[16,9]"
                  style="height: 400px;width: 800px;"
              ></vue-cropper>
              <!-- 完成按钮 -->
              <el-button v-show="showCropper" class="blog_post" type="primary" @click="handleFinish">完成</el-button>
            </el-col>
          </el-row>
          <el-row style="margin-bottom: 20px;">
            <el-col :span="12">
              <span>选择文章标签</span>
              <el-checkbox-group v-model="selectedTags">
                <el-checkbox label="智能合约" name="tag">智能合约</el-checkbox>
                <el-checkbox label="DApps" name="tag">DApps</el-checkbox>
                <el-checkbox label="Web3.0" name="tag">Web3.0</el-checkbox>
                <el-checkbox label="Coin" name="tag">Coin</el-checkbox>
              </el-checkbox-group>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" style="height: 200px;">
              <el-button type="primary" native-type="submit" class="blog_post">发布文章</el-button>
            </el-col>
          </el-row>
        </form>
      </el-main>
    </el-container>
    <el-aside class="aside" width="150px"></el-aside>
  </el-container>
</div>
</template>

<script>
import axios from "axios";
import { ref } from 'vue';
import {
  // necessary extensions
  Doc,
  Text,
  Paragraph,
  //________________________
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  BulletList,
  OrderedList,ElementTiptap,
  Link,
  Image,
  CodeBlock,
} from 'element-tiptap-vue3-fixed';
import {Picture} from "@element-plus/icons-vue";

export default {
  name:"BlogWriting",
  components: {
    Picture,
    ElementTiptap,
  },
  setup() {
    const content = ref(`
      <h1>标题</h1>
      <p>正文</p>
      <h6>注:本富文本编辑器并没有ctrl+z功能，请谨慎编写，开始编写时请删掉此部分</h6>
    `);

    // editor extensions
    // they will be added to menubar and bubble menu by the order you declare.
    const extensions = [
      Doc,
      Text,
      Paragraph,
      Heading.configure({ level: 5 }),
      Bold.configure({ bubble: true }), // render command-button in bubble menu.
      Underline.configure({ bubble: true, menubar: false }), // render command-button in bubble menu but not in menubar.
      Italic,
      Strike,
      BulletList,
      OrderedList,
      Link,
      Image,
      CodeBlock,
    ];

    return { content, extensions };
  },
  data(){
    return{
      username:"",
      imageUrl:"",
      title:"",
      summary:"",
      selectedTags: [],
      showCropper:false,
    }
  },
  created() {
  },
  mounted() {
    this.fetchUserInfo()
  },
  methods:{
    fetchUserInfo(){
      const token=localStorage.getItem('token')
      const config={
        headers:{
          Authorization:`Bearer ${token}`
        }
      }
      axios.get('http://47.113.225.21:1145/api/all_userinfo',config)
          .then(response=>{
            this.username=response.data.username;
            console.log('获取用户信息成功')
          })
          .catch(error=>{
            this.$message.error("权限不足，请先登录")
            this.$router.push({name:"HomePage"})
            console.log('获取用户信息失败',error)
          })
    },
    submitForm() {
      // 检查标题是否为空和封面是否已上传
      if (!this.title.trim()) {
        this.$message.error('请填写文章标题');
        return;
      }
      if (!this.imageUrl) {
        this.$message.error('请上传封面');
        return;
      }
      const formData=new FormData();
      formData.append('title',this.title.trim())
      formData.append('summary',this.summary.trim())
      formData.append('content',this.content)
      formData.append('imageUrl',this.imageUrl)
      formData.append('username',this.username)
      const tagsString = this.selectedTags.join(',');
      formData.append('tags', tagsString)
      const token=localStorage.getItem('token')
      axios.post('http://47.113.225.21:1145/api/create_post',formData,{
        headers:{
          Authorization:`Bearer ${token}`
        }
      })
          // eslint-disable-next-line no-unused-vars
          .then(response=>{
            // 处理成功响应
            console.log('发布文章成功');
            this.$message.success("发布文章成功");
            this.$router.push({name:"HomePage"})
          })
          .catch(error => {
        // 处理失败响应
        console.error('发布文章失败:', error);
        this.$message.error('发布文章失败,请联系站长')
      });

    },
    chooseCover(){
      this.$refs.coverInput.click();
    },
    handleCoverChange(event){
      const file = event.target.files[0];
      const allowTypes=['image/png'];
      const maxFileSize=2*1024*1024;
      if (!file) return;
      if(!allowTypes.includes(file.type)){
        this.$message.error("请选择.png格式文件")
        return;
      }
      if(file.size>maxFileSize){
        this.$message.error("请选择大小小于等于2MB的文件")
        return;
      }
      const reader = new FileReader();
      reader.onload = () => {
        this.imageUrl = reader.result;
        this.showCropper = true;
      };
      reader.readAsDataURL(file);
    },
    handleFinish() {
      // 获取裁剪后的头像数据
      this.$refs.cropper.getCropData(data=>{
        this.imageUrl=data;
      })
      // 隐藏cropper组件
      this.showCropper = false;
    }
  },

}
</script>

<style scoped>
.aside{
  background-color: #ffffff;
  width: 200px;
  height: 100%
}
.main{
  width: 1050px;
  min-height: calc(100vh - 65px);
  overflow-y: auto;
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
}
:deep(.el-tiptap-editor__command-button--active) {
  color: white;
  background-color: black;
}
:deep(.el-tiptap-editor__command-button:hover) {
  color: white;
  background-color: #606266;
}
.el-textarea{
  --el-input-focus-border: #000000;
  --el-input-focus-border-color: #000000;
}
.blog_post{
  background-color: black;
  color: #ffffff;
  border-color: black !important;
}
.blog_post:hover{
  background-color: #606266;
  color: #ffffff;
  border-color: black !important;
}
.blog_post:focus{
  background-color: black !important;
  color: #ffffff !important;
  border-color: black !important;
}
.el-checkbox__input.is-checked .el-checkbox__inner{
  background-color: black !important;
  border-color: black !important;
}
.el-checkbox__input.is-checked+.el-checkbox__label{
  color: #303133 !important;
}
.el-checkbox{
  --el-checkbox-checked-text-color: #303133;
  --el-checkbox-checked-input-border-color: #303133;
  --el-checkbox-checked-bg-color: #303133;
  --el-checkbox-checked-icon-color: var(--el-color-white);
  --el-checkbox-input-border-color-hover: #303133
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
</style>